﻿using Newtonsoft.Json;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using System.Windows;
using TransformerManager.Shared.Dto.Transformer;
using TransformerManager.Shared.Helper.HttpParams;
using TransformerManager.WPF.Common.Helper.Events;
using TransformerManager.WPF.Common.Http.Service;

namespace TransformerManager.WPF.Common.ViewModels
{
    public class ProjectInfoTemplateViewModel : BindableBase, INavigationAware
    {
        private readonly IEventAggregator _eventAggregator;
        private readonly IDialogService _dialogService;
        private readonly IUserInfoService _userInfoService;

        public ProjectInfoTemplateViewModel(
            IDialogService dialogService,
            IUserInfoService userInfoService,
            IEventAggregator eventAggregator)
        {
            _dialogService = dialogService;
            _eventAggregator = eventAggregator;
            _userInfoService = userInfoService;

            // 用于判断当前页面是否可以编辑,该事件由DetailInfoTemplate页面
            // 和CreateNewProject页面的编辑按钮和取消按钮触发
            _eventAggregator.GetEvent<DetailInfoPageEvent>().Subscribe(IsCurrentPageEditable);

            InitAllCmd();
        }

        #region Command

        public DelegateCommand GetUsersCmd { private set; get; }

        #endregion


        #region 方法的定义

        private bool _isContentEditable = false;
        public bool IsContentEditable
        {
            set
            {
                _isContentEditable = value;

                RaisePropertyChanged();
            }
            get
            {
                return _isContentEditable;
            }
        }

        private Visibility _isLoadingVisible = Visibility.Collapsed;
        public Visibility IsLoadingVisible
        {
            set
            {
                _isLoadingVisible = value;

                RaisePropertyChanged();
            }
            get
            {
                return _isLoadingVisible;
            }
        }

        private UserBasicParams _user;
        public UserBasicParams User
        {
            set
            {
                _user = value;

                RaisePropertyChanged();
            }
            get
            {
                return _user;
            }
        }

        private TransformerDto _transformerDto;
        public TransformerDto TransformerDto
        {
            set
            {
                _transformerDto = value;

                RaisePropertyChanged();
            }
            get
            {
                return _transformerDto;
            }
        }


        #endregion


        #region 函数的定义

        private void InitAllCmd()
        {

            GetUsersCmd = new DelegateCommand(async () =>
            {
                IsLoadingVisible = Visibility.Visible;
                var userlist = await RetreveUserList();
                IsLoadingVisible = Visibility.Collapsed;

                var dialogParams = new DialogParameters() { { "UserList", userlist } };
                _dialogService.ShowDialog("UserListDialog", dialogParams, r =>
                {
                    if (r.Result == ButtonResult.OK)
                    {
                        User = r.Parameters.GetValue<UserBasicParams>("SelectedUser");
                        TransformerDto.UserId = User.UserId;
                    }
                });
            });

        }

        private async Task<ObservableCollection<UserBasicParams>> RetreveUserList()
        {
            // 获取主设列表
            var result = await _userInfoService.GetUsersAsync(string.Empty, true, 1, 30);

            if (result == null) return new ObservableCollection<UserBasicParams>();

            return JsonConvert.DeserializeObject<ObservableCollection<UserBasicParams>>(result.Result.ToString());
        }

        /// <summary>
        /// 初始化控件的变量
        /// </summary>
        private async Task InitLeadEngineerInfo()
        {
            // 获取变压器主设信息
            if (!string.IsNullOrEmpty(TransformerDto.UserId))
            {
                // 根据用户ID请求其信息
                var result = await _userInfoService.GetUserInfoByIdAsync(TransformerDto.UserId);
                if (result == null) return;

                User = result;
            }
            else
            {
                User = new UserBasicParams();
            }
        }

        private void IsCurrentPageEditable(bool isEditable)
        {
            IsContentEditable = isEditable;
        }

        #endregion


        #region 接口实现的函数

        public async void OnNavigatedTo(NavigationContext navigationContext)
        {
            await InitLeadEngineerInfo();

            // 进入详情界面则通知导航栏下的刷新按钮可以编辑
            _eventAggregator.GetEvent<ReloadXmlDataEnableEvent>().Publish(true);
        }

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {

        }

        #endregion


    }
}
